﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlServerCe;
using System.IO;
using System.Data;
using System.Resources;
using PeapodCatcher.Properties;
using System.Windows;


namespace PeapodCatcher
{
    public class DataBaseHealthCheck
    {
        public static void VerifyDatabase()
        {
            SqlCeConnection conn = new SqlCeConnection(Common.ConnectionString);

            try
            {
                if (!System.IO.File.Exists(conn.Database))
                {
                    SqlCeEngine engine = new SqlCeEngine(conn.ConnectionString);
                    engine.CreateDatabase();
                    CreateInitialDatabaseObjects(conn);

                }
            }
            finally
            {
                if (conn != null && conn.State != ConnectionState.Closed)
                {
                    conn.Close();
                }
            }
        }

        private static void CreateInitialDatabaseObjects(SqlCeConnection conn)
        {
            string[] commands = Resources.DatabaseScript.Split(new string[]{"GO"}, StringSplitOptions.RemoveEmptyEntries);
            SqlCeCommand cmd = new SqlCeCommand();
            cmd.Connection = conn;
            conn.Open();
            foreach(string command in commands) {
                cmd.CommandText = command;
                cmd.ExecuteNonQuery();
            }
            conn.Close();
        }
    }
}
